import { request, getFullImageUrl } from '../../utils/request';
export default {
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: String,
      required: true
    }
  },
  data() {
    // 获取当前日期时间作为初始值
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hour = now.getHours().toString().padStart(2, '0');
    const minute = now.getMinutes().toString().padStart(2, '0');
    const currentDateTime = `${year}-${month}-${day}`;
    const currentTime = `${hour}:${minute}`;

    return {
      formData: {
        title: '',
        address: '',
        start_time: currentDateTime,
        time: currentTime,
        end_time: currentDateTime,
        endTime: currentTime,
        skill_desc: '',
        person_req: '',
        people_num: 0,
        salary: null,
        task_id: this.orderId,
        
      },
      successContent: 'null',
      originalSalary: null, // 保存原始酬金金额
      originalPeopleNum: null, // 保存原始人数
      timeError: false,
      timeErrorMessage: '',
      oldTotal: 0, // 保存订单原始总金额
        newTotal: 0, // 保存订单修改后的总金额
        totalDiff: 0, // 保存订单总金额差异
        showPriceDiffPopup: false, // 控制差价确认弹窗显示/隐藏
        showCancelRecruitmentPopup: false, // 控制取消招募确认弹窗显示/隐藏
        showSuccessWindow: false // 控制成功提示弹窗显示/隐藏
    };
  },
  watch: {
    orderId: {
      handler(newVal) {
        if (newVal) {
          this.formData.task_id = newVal;
          this.loadOrderDetails();
        }
      },
      immediate: true
    }
  },
  created() {
    // 添加事件监听
    this.$bus.$on('locationUpdated', this.handleLocationUpdate);
  },
  beforeDestroy() {
    // 移除事件监听，防止内存泄漏
    this.$bus.$off('locationUpdated', this.handleLocationUpdate);
  },
  methods: {
    getFullImageUrl,
    // 添加处理地址输入的方法
    handleLocationInput() {
      // 可以在这里添加地址输入的处理逻辑
    },
    // 加载订单详情
    loadOrderDetails() {
      request({
        url: 'Parttimejobs/info',
        method: 'POST',
        data: {
          task_id: this.formData.task_id
        }
      }).then(res => {
        if (res.code == 200) {
          this.formData.title = res.data.title;
          this.formData.address = res.data.address;
          this.formData.start_time = res.data.start_time;
          this.formData.time = res.data.time;
          this.formData.end_time = res.data.end_time;
          this.formData.endTime = res.data.endTime;
          this.formData.skill_desc = res.data.skill_desc;
          this.formData.person_req = res.data.person_req;
          this.formData.people_num = res.data.people_num;
          this.formData.salary = res.data.salary;
          this.originalSalary = res.data.salary; // 保存原始酬金金额
          this.originalPeopleNum = res.data.people_num; // 保存原始人数
          this.formData.latitude = res.data.latitude;
          this.formData.longitude = res.data.longitude;
        }
      })
    },
    // 日期选择变化
    bindDateChange(e) {
      this.formData.start_time = e.detail.value;
    },
    // 结束日期选择变化
    bindEndDateChange(e) {
      this.formData.end_time = e.detail.value;
    },
    // 时间选择变化
    bindTimeChange(e) {
      this.formData.time = e.detail.value;
    },
    // 结束时间选择变化
    bindEndTimeChange(e) {
      this.formData.endTime = e.detail.value;
    },
    // 关闭弹窗
    closeModal() {
      this.$emit('update:showModal', false);
    },
    
    // 取消招募
    cancelRecruitment() {
      // 显示自定义弹窗
      this.showCancelRecruitmentPopup = true;
    },
    
    // 关闭取消招募弹窗
    closeCancelRecruitmentPopup() {
      this.showCancelRecruitmentPopup = false;
    },
    
    // 确认取消招募
    confirmCancelRecruitment() {
      this.closeCancelRecruitmentPopup();
      uni.showLoading({ title: '处理中...' });
      
      request({
        url: 'WorkerPosts/cancelRecruitment',
        method: 'POST',
        data: {
          job_id: this.formData.task_id
        },
        success: (result) => {
          uni.hideLoading();
          if (result.data && result.data.code === 200) {
            this.successContent = '招募已取消';
            this.showSuccessWindow = true;
            // 2秒后自动隐藏成功提示
            setTimeout(() => {
              this.showSuccessWindow = false;
              this.successContent = '';
            }, 2000);
            this.closeModal();
            this.$emit('recruitmentCanceled', this.formData.task_id);
          } else {
            uni.showToast({ title: result.data.msg || '取消失败', icon: 'none' });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('取消招募失败:', err);
          uni.showToast({ title: '网络错误，请重试', icon: 'none' });
        }
      });
    },
    // 确认修改
    confirmModify() {
      // 检查表单是否有效
      if (this.validateForm()) {
        // 检查金额和人数变化
        const newSalary = parseFloat(this.formData.salary);
        const oldSalary = parseFloat(this.originalSalary);
        const newPeopleNum = this.formData.people_num || 1;
        const oldPeopleNum = this.originalPeopleNum || 1;
        const newTotal = newSalary * newPeopleNum;
        const oldTotal = oldSalary * oldPeopleNum;
        const totalDiff = newTotal - oldTotal;

        // 如果总金额有变化，需要进行多退少补
        if (totalDiff !== 0) {
          this.handleSalaryChange(totalDiff, oldTotal, newTotal);
        } else {
          // 总金额没有变化，直接提交修改
          this.submitOrderUpdate();
        }
      }
    },

    // 处理金额变化
    handleSalaryChange(totalDiff, oldTotal, newTotal) {
      this.oldTotal = oldTotal;
      this.newTotal = newTotal;
      this.totalDiff = totalDiff;
      // 显示自定义弹窗
      this.showPriceDiffPopup = true;
    },
    
    // 关闭差价弹窗
    closePriceDiffPopup() {
      this.showPriceDiffPopup = false;
    },
    
    // 确认差价处理
    confirmPriceDiff() {
      this.closePriceDiffPopup();
      if (this.totalDiff > 0) {
        // 用户确认补差价，提交修改并处理支付
        this.submitOrderUpdateWithPayment(this.totalDiff);
      } else {
        // 用户确认退还差价，提交修改
        this.submitOrderUpdate();
      }
    },

    // 提交订单修改
    submitOrderUpdate() {
      uni.showLoading({ title: '修改中...' });

      request({
        url: 'Parttimejobs/edit',
        method: 'POST',
        data: this.formData,
        success: (res) => {
          uni.hideLoading();
          if (res.data.code == 200) {
            uni.showToast({ title: '修改成功', icon: 'success' });
            this.closeModal();
            // 传递修改后的酬金数据
            this.$emit('modifySuccess', this.formData.salary);
          } else {
            uni.showToast({ title: res.data.msg || '修改失败', icon: 'none' });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({ title: '网络错误', icon: 'none' });
        }
      });
    },

    // 提交订单修改并处理差价支付
    submitOrderUpdateWithPayment(amount) {
      uni.showLoading({ title: '处理中...' });

      // 先创建支付订单
      request({
        url: '/Payment/createAdditionalPayment',
        method: 'POST',
        data: {
          additional_amount: amount,
          task_id: this.formData.task_id,
          openid: uni.getStorageSync('openid')
        },
        success: (payRes) => {
          uni.hideLoading();
          if (payRes.data && payRes.data.code === 200) {
            // 调用微信支付
            uni.requestPayment({
              ...payRes.data.data,
              success: () => {
                // 支付成功后提交订单修改
                this.submitOrderUpdate();
              },
              fail: (err) => {
                console.log('支付失败:', err);
                uni.showToast({ title: '支付失败，订单未修改', icon: 'none' });
              }
            });
          } else {
            uni.showToast({ title: '创建支付订单失败', icon: 'none' });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('创建支付订单失败:', err);
          uni.showToast({ title: '网络错误，请重试', icon: 'none' });
        }
      });
    },
    // 表单验证
    validateForm() {
      // 基础表单验证
      const basicValid = !!this.formData.title &&
        !!this.formData.address &&
        !!this.formData.start_time &&
        !!this.formData.time &&
        !!this.formData.end_time &&
        !!this.formData.endTime &&
        this.formData.people_num > 0;

      // 时间范围验证
      this.timeError = false;
      this.timeErrorMessage = '';

      if (basicValid) {
        const start = new Date(`${this.formData.start_time}T${this.formData.time}`);
        const end = new Date(`${this.formData.end_time}T${this.formData.endTime}`);
        const now = new Date();

        if (start >= end) {
          this.timeError = true;
          this.timeErrorMessage = '结束时间不能早于开始时间';
          uni.showToast({ title: this.timeErrorMessage, icon: 'none' });
          return false;
        }
      } else {
        uni.showToast({ title: '请填写所有必填字段', icon: 'none' });
        return false;
      }

      return basicValid && !this.timeError;
    },
    // 处理位置更新的方法
    handleLocationUpdate(data) {
      this.formData.address = data.address;
      this.formData.latitude = data.latitude;
      this.formData.longitude = data.longitude;
    }
  }
};